<?php
namespace utils;

use store\StorageType;

class WebWriter
{
    var $cacheSize=1048576;//1MB

    public function write($pathSvr,$offset,$size)
    {
        $reader = ConfigReader::blockReader();
        if($reader->storage == StorageType::Minio)
        {
            $this->writeMinio($reader, $pathSvr, $offset, $size);
        }
        else if($reader->storage==StorageType::OSS)
        {
            $this->writeOSS($reader, $pathSvr, $offset, $size);
        }
        else
        {
            $this->writeIO($reader, $pathSvr, $offset, $size);
        }
    }
    
    public function writeMinio($fr,$id,$offset,$size)
    {
        set_time_limit(0);
        $data =  $fr->read($id,intval($offset), intval($size));
        print($data);
        flush();
        ob_flush();
    }
    
    public function writeOSS($fr,$id,$offset,$size)
    {
        set_time_limit(0);
        $data =  $fr->read($id,intval($offset), intval($size));
        print($data);
        flush();
        ob_flush();
    }
    
    public function writeIO($fr,$pathSvr,$offset,$blockSize)
    {
        set_time_limit(0);
        // 总共需要下载的长度
        $dataToRead = $blockSize;
        //每次读1MB，然后传给终端
        $buf_size = min($this->cacheSize, $blockSize);
        while ($dataToRead > 0)
        {
            $data =  $fr->read($pathSvr,intval($offset), intval($buf_size));
            print($data);
            flush();
            ob_flush();
            
            $dataToRead -= $buf_size;
            $offset += $buf_size;//
            $buf_size = $dataToRead < $buf_size ? $dataToRead : $buf_size;
        }
    }
}
?>